// 引入fs模块

const fs = require('fs')

// 遍历文件夹data,判断文件是否已经存在
let fileIsExist = (data) => {
    return new Promise((resolve, reject) => {
        let fileName = data.sender + '&' + data.rejector
        fs.readdir('./data', (err, arr) => {
            if (err) {
                return false
            }
            // 判断文件是否已经存在
            let res = arr.includes(fileName)
            resolve(res)
        })
    })

}
// 根据消息中的对象创建文件
let createFile = async (data) => {
    let fileName1 = data.sender + '&' + data.rejector
    let fileName2 = data.rejector + '&' + data.sender
    // 判断文件是否存在
    let res = await fileIsExist(data)
    if (res) {
        console.log('文件已存在，不再创建')
    } else {
        data.message = 'hello'
        data.sendTime = Date.now()
        fs.writeFile('./data/' + fileName1, JSON.stringify(data), () => {
            console.log('创建文件成功1')
        })
        fs.writeFile('./data/' + fileName2, JSON.stringify(data), () => {
            console.log('创建文件成功2')
        })
    }
}
// 向现有文件中添加记录
let appendMessage = (data) => {
    let fileName1 = data.sender + '&' + data.rejector
    let fileName2 = data.rejector + '&' + data.sender
    fs.appendFile('./data/' + fileName1, ',' + JSON.stringify(data), () => {
        console.log('添加记录成功1')
    })
    fs.appendFile('./data/' + fileName2, ',' + JSON.stringify(data), () => {
        console.log('添加记录成功2')
    })
}

// 读取文件内容
let getUserHistoryMessages = (data) => {
    return new Promise((resolve, reject) => {
        let fileName = data.sender + '&' + data.rejector;
        fs.readFile('./data/' + fileName, 'utf-8', (err, res) => {
            if (err) {
                resolve('')
            } else {
                resolve('[' + res + ']')
            }
        })
    })
}

module.exports = {
    createFile,
    appendMessage,
    fileIsExist,
    getUserHistoryMessages,
}

